import React, { useState, useEffect } from 'react';
import { connect, Dispatch } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import ProCard from '@ant-design/pro-card';
import { PARAM_LIST, PARAM_ADD, PARAM_UPDATE, PARAM_UNMOUNT } from '@/actions/param';
import AGrid, { AGridButtonCallBackModel } from '@/components/SelfComp/AGrid';
import { ConnectState } from '@/models/connect';
import { FlagEnum } from '@/types/global';
import { ParamItem } from '@/types/param';
import ParamQueryForm from './components/ParamQueryForm';
import AddParamModal from './components/AddParamModal';
import UpdateParamModal from './components/UpdateParamModal';

interface ParamListProps {
  dispatch: Dispatch;
  paramList: ParamItem[],
  total: number,
  loading: boolean;
  pageSize: number;
  addLoading: boolean;
  updateLoading: boolean;
}

const EMPTY: ParamItem = {
  paramId: '',
  paramName: '',
  paramKey: '',
  paramValue: '',
  paramValueDesc: '',
  paramStates: ''
}

/**
 * 参数管理，用于配置默认密码，登录允许密码最大错误次数等参数
 */
const ParamList: React.FC<ParamListProps> = (props) => {
  // 新增弹窗
  const [addModalVisible, setAddModalVisible] = useState<boolean>(false);
  const [paramFormData, setParamFormData] = useState<ParamItem>(EMPTY);
  const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
  const [selectedRows, setSelectedRows] = useState<ParamItem[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [queryParam, setQueryParam] = useState<ParamItem>();
  // 默认为10
  const [pageSize, setPageSize] = useState<number>(10);
  const [flag, setFlag] = useState<FlagEnum>('edit');

  useEffect(() => {
    console.info('ParamList.useEffect');
    // 查询本页面需所有参数
    fetchAllParam(1, pageSize, queryParam);
    return () => {
      const { dispatch } = props;
      dispatch(PARAM_UNMOUNT({}));
    }
  }, []);

  const columns = [
    {
      title: '参数名称',
      dataIndex: 'paramName',
      width: 250,
    },
    {
      title: '参数键名',
      dataIndex: 'paramKey',
      width: 300,
    },
    {
      title: '参数键值',
      dataIndex: 'paramValue',
      width: 300,
    },
    {
      title: '参数键值描述',
      dataIndex: 'paramValueDesc',
    }
  ];

  /**
   * 打开参数新增窗口
   */
  const openAddParamModal = () => {
    setAddModalVisible(true);
  }

  const handleAddModalOk = async (record: ParamItem) => {
    console.log(record);
    const { dispatch } = props;
    const res = await dispatch(PARAM_ADD(record));
    console.info(res);
    if (res) {
      setAddModalVisible(false);
      fetchAllParam(1, pageSize, queryParam);
    }
  }

  const handleAddModalCancel = () => {
    setAddModalVisible(false);
  };

  /**
   * 修改参数，打开参数修改窗口
   */
  const openUpdateParamModal = (records: ParamItem[], flag: FlagEnum) => {
    // 表格选中内容
    // console.info('openUpdateParamModal');
    // console.info(records);
    const row = records[0];
    const paramFormData = {
      ...row,
    };
    setParamFormData(paramFormData);
    setFlag(flag);
    setUpdateModalVisible(true);
  }

  /**
   * 更新面板的确定事件
   * @param {*} record 更新表单
   */
  const handleUpdateModalOk = async (record: ParamItem) => {
    // console.log('handleUpdateModalOk');
    // console.log(record);
    // console.info(paramFormData);
    if (flag === 'edit') {
      const { dispatch } = props;
      const res = await dispatch(PARAM_UPDATE(record));
      console.info(res);
      if (res) {
        setParamFormData(EMPTY);
        setUpdateModalVisible(false);
        fetchAllParam(1, pageSize, queryParam);
      }
    } else {
      setParamFormData(EMPTY);
      setUpdateModalVisible(false);
    }
  }

  const handleUpdateModalCancel = () => {
    setParamFormData(EMPTY);
    setUpdateModalVisible(false);
  };

  /**
   * 根据条件分页查询表格数据
   * @param {*} record 条件
   */
  const handleFetchParam = (record: ParamItem) => {
    console.log(record);
    const queryParam = {
      ...record
    };
    // 查询条件保存起来，方便点击页码时使用
    // setState回调方法，保证先更新state
    setQueryParam(queryParam);
    fetchAllParam(1, pageSize, queryParam);
  }

  /**
   * 页码改变的回调，参数是改变后的页码及每页条数
   * @param page 改变后的页码，上送服务器端
   * @param pageSize 每页数据条数
   */
  const onPageNumAndSizeChange = (page: number, pageSize: number) => {
    // console.log(page, pageSize);
    setPageSize(pageSize);
    fetchAllParam(page, pageSize, queryParam);
  };

  /**
   * 分页查询系统参数信息
   * @param {*} pageNum 页码
   * @param {*} pageSize 每页记录条数
   */
  const fetchAllParam = (pageNum: number, pageSize: number, queryParam?: ParamItem) => {
    const { dispatch } = props;
    dispatch(PARAM_LIST({
      ...queryParam,
      pageSize,
      pageNum
    }));
  }

  /**
   * 处理按钮点击回调事件
   * @param {*} callBacModel 数据包
   */
  const handleBtnCallBack = (callBackModel: AGridButtonCallBackModel<ParamItem>) => {
    // console.log('handleBtnCallBack');
    // console.log(callBackModel);
    // btn 按钮
    // keys 表格勾选数组
    const { code } = callBackModel;
    // 新增
    if (code === 'add') {
      openAddParamModal();
      return;
    }
    // 修改
    if (code === 'edit') {
      const { rows } = callBackModel;
      openUpdateParamModal(rows, 'edit');
      return;
    }
    // 删除
    if (code === 'delete') {
      // const { rows } = callBackModel;
      // 调用删除服务，删除勾选数据
      return;
    }
    // 查看
    if (code === 'view') {
      const { rows } = callBackModel;
      openUpdateParamModal(rows, 'view');
      return;
    }
  }

  /**
   * 表格勾选回调函数
   * @param {*} rows 表格选中数据集合
   */
  const onSelectRow = (keys: React.Key[], rows: ParamItem[]) => {
    setSelectedRowKeys(keys);
    setSelectedRows(rows);
  };

  const code = 'param-list';
  const { paramList, loading, total, addLoading, updateLoading } = props;
  const rowKey = (record: ParamItem) => record.paramId;

  return (
    <PageContainer>
      <ProCard title="参数列表" headerBordered>
        <ParamQueryForm colon={false} onSubmit={handleFetchParam} loading={loading} />
        <AGrid<ParamItem>
          code={code}
          btnCallBack={handleBtnCallBack}
          columns={columns}
          rowKey={rowKey}
          dataSource={paramList}
          total={total}
          loading={loading}
          onSelectRow={onSelectRow}
          pkField='paramId'
          onPageNumAndSizeChange={onPageNumAndSizeChange}
        />
      </ProCard>
      {
        !addModalVisible ? null :
        <AddParamModal
          colon={false}
          modalTitle='新增参数'
          modalWidth={1000}
          modalVisible={addModalVisible}
          loading={addLoading}
          onHandlerOK={handleAddModalOk}
          onHandlerCancel={handleAddModalCancel}
        />
      }
      {
        !updateModalVisible ? null :
        <UpdateParamModal
          colon={false}
          modalTitle=''
          modalWidth={1000}
          modalVisible={updateModalVisible}
          flag={flag}
          loading={updateLoading}
          formData={paramFormData}
          onHandlerOK={handleUpdateModalOk}
          onHandlerCancel={handleUpdateModalCancel}
        />
      }
    </PageContainer>
  );
}

export default connect(({ params: { rows, ...res }, loading }: ConnectState) => ({
  ...res,
  paramList: rows,
  loading: loading.effects['params/fetchAllParam'],
  addLoading: loading.effects['params/addParam'],
  updateLoading: loading.effects['params/updateParam'],
}))(ParamList);